// SoundManager.java
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.sound.sampled.*;

public class SoundManager {
    private static Map<String, Clip> sounds = new HashMap<>();
    private static Clip backgroundMusic;

    static {
        loadSound("shoot.wav");
        loadSound("explosion.wav");
        loadSound("gameover.wav");
        loadSound("start.wav");
        loadSound("background.wav");
    }

    public static void loadSound(String soundName) {
        try {
            // 使用类加载器加载资源
            InputStream audioStream = SoundManager.class.getClassLoader().getResourceAsStream("sounds/" + soundName);
            if (audioStream == null) {
                System.err.println("Sound not found: " + soundName);
                return;
            }

            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioStream);
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            sounds.put(soundName, clip);

            System.out.println("Sound loaded successfully: " + soundName);
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            System.err.println("Error loading sound: " + soundName);
            e.printStackTrace();
        }
    }

    public static void playSound(String soundName) {
        Clip clip = sounds.get(soundName);
        if (clip != null) {
            clip.setFramePosition(0);
            clip.start();
        } else {
            System.err.println("Sound not found: " + soundName);
        }
    }

    public static void playBackgroundMusic(String musicName) {
        try {
            if (backgroundMusic != null && backgroundMusic.isRunning()) {
                backgroundMusic.stop();
            }

            InputStream audioStream = SoundManager.class.getClassLoader().getResourceAsStream("sounds/" + musicName);
            if (audioStream == null) {
                System.err.println("Music not found: " + musicName);
                return;
            }

            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioStream);
            backgroundMusic = AudioSystem.getClip();
            backgroundMusic.open(audioInputStream);
            backgroundMusic.loop(Clip.LOOP_CONTINUOUSLY);

            System.out.println("Background music started: " + musicName);
        } catch (Exception e) {
            System.err.println("Error playing background music: " + musicName);
            e.printStackTrace();
        }
    }

    public static void stopBackgroundMusic() {
        if (backgroundMusic != null && backgroundMusic.isRunning()) {
            backgroundMusic.stop();
            System.out.println("Background music stopped");
        }
    }
}